var api = require('../../../utils/api.js')
var $ = require('../../../utils/util.js')
var regeneratorRuntime = require('../../../utils/runtime.js')
var app = getApp()
var Store = app.Store

Page({
  data: {
    form:{}, // redux传过来的参数
    steps: [],
    active:0,
    mainEquipImage: '', // 图片1
    partEquipImage: '', // 图片2
    nameplateImage: '', // 图片3
    urls:['https://img.yzcdn.cn/vant/cat.jpeg'],
    signImg:'',
    nexFlag:true,
    isShow:false,
    locked:false,
    timer:null,
    currentStep:'',
    applyReason:'',
    applyStartTime: "",
    applyEndTime: "",
    dateNum:'',
    type:''
  },
  onLoad: function (options) {
    this.setData({dateNum:new Date().getTime()})
    if('ticketNumber' in options){
      this.setData({type:options.type,ticketNumber:options.ticketNumber})
      this.getOperateList()
      this.setData({
        timer:setInterval(()=>{
          this.getOperateList()
        },10000)
      })
      
    }
  },
  onUnload(){
    clearInterval(this.data.timer)
  },
  onShow: function () {
    var form = Store.getState().formInfor.form
    var key = form.key
    console.log(form)
    switch (key) {
      case 'operateSign': // 获取签发人签名  
        this.setData({
          signImg: form.selected,
        })
        break 
      default:
        this.setData({
          signImg: wx.getStorageSync('signUrl'),
        })
        break;
    }
    console.log(this.data.signImg)
  },
showTickets(e) {
  const {type,item,idx}=$.detail(e)
  wx.previewImage({
    current: '', // 当前显示图片的链接，不填则默认为urls的第一张
    urls: this.data.urls // 需要预览的图片链接列表
  })
  
},  
getOperateList(){
  api.$get(api.operateTicket.ticketOperationList,{
    ticketNumber:this.data.ticketNumber,
  }).then((res) => {
    if(res.code==200){
      const findIdx=res.data.findIndex((item)=>item.taskStatus==0)
       if(findIdx>0){
          const last= res.data[findIdx-1]
          if((last.tagGrounded!= 0 && last.tagGroundedConfirmed==1)|| (last.tagNoClosing!= 0 && last.tagNoClosingConfirmed==1) ||(last.tagWorkHere!= 0 && last.tagWorkHereConfirmed==1) ||(last.requiresInterlock!= 0 && last.interlockConfirmed==1)  ||(last.checkSwitch!= 0 && last.checkSwitchConfirmed==1) ){
            console.log("status 1")
            this.setData({active:findIdx,taskId:res.data[findIdx].taskId})
          }else if(last.tagGrounded==0 && last.tagNoClosing==0 && last.tagWorkHere==0 && last.requiresInterlock==0 && last.checkSwitch==0 ){
            console.log("status 2")
            this.setData({active:findIdx,taskId:res.data[findIdx].taskId})
          }else {
            console.log("status 3")
            this.setData({active:findIdx-1,taskId:res.data[findIdx-1].taskId})
          }
        }else if(findIdx==0){
            this.setData({active:findIdx,taskId:res.data[findIdx].taskId})
        }else{
            this.setData({active:res.data.length,taskId:res.data[res.data.length-1].taskId})
        }
      console.log(this.data.active)
      this.setData({steps:res.data.map((item,index)=>{
        return {...item,text:`步骤${index+1}--------------------------${index>=this.data.active?'未审核':'已审核'}`,desc:item.taskDescription}
        }),
        
      })
    }
  })
},
stepUpload(e){
  console.log(e)
  this.setData({currentStep:this.data.steps[e.detail]})
  const steps=this.data.steps[e.detail]
  this.setData({
    mainEquipImage:steps.tagNoClosingDevicePicture||steps.tagGroundedDevicePicture||steps.tagWorkHereDevicePicture||steps.interlockDevicePicture,
    taskId:steps.taskId
  })
  
  if(this.data.active==e.detail){
    var that=this
    if(steps.requiresInterlock==1){
      wx.showModal({
        title: '提示',
        confirmText:'申请开锁',
        cancelText:'上传图片',
        content:'请先申请操作锁权限后再上传图片',
        success (res) {
          if (res.confirm) {
            api.$get(api.operateTicket.applyUnLocking,{
              ticketNumber:that.data.ticketNumber,
              taskId:that.data.taskId,
            }).then((res) => {
              if(res.code==200){
                $.linkurl(`/pages/lockMange/lockScan/lockScan`) 
              }
            })
          } else if (res.cancel) {
            that.setData({isShow:true})
          }
        }
      })
    }else if((steps.tagNoClosing||steps.tagGrounded||steps.tagWorkHere||steps.checkSwitch)) {
      that.setData({isShow:true})
    }else{
    }
  }
  
},
upPicsHandle(e) { // ##图片组件传出来的数据##
  var { pics, key } = e.detail
  console.log(pics, key)
  this.setData({
    [key]: pics.length>0?pics[0]:[]
  })
 
},
esureUpImage(){
  if(!Boolean(this.data.mainEquipImage)){
    $.toast('请先上传图片！')
    return false
  }
  api.$get(api.operateTicket.operationSubmitTask,{
    ticketNumber:this.data.ticketNumber,
    taskId:this.data.taskId,
    imageUrl:this.data.mainEquipImage||''
  }).then((res) => {
    if(res.code==200){
      $.toast('已上传图片！等待审核')
      if(this.data.currentStep.tagNoClosing==1){
        this.signNoClosing()
      }
      if(this.data.currentStep.tagNoClosing==2){
        this.unSignNoClosing()
      }
      if(this.data.currentStep.tagGrounded==1){
        this.signTagGrounded()
      }
      if(this.data.currentStep.tagGrounded==2){
        this.unSignTagGrounded()
      }
      if(this.data.currentStep.tagWorkHere==1){
        this.signWorkHere()
      }
      if(this.data.currentStep.tagWorkHere==2){
        this.unSignWorkHere()
      }
    }
  })
},
nextProcess(){
  console.log(this.data.mainEquipImage)
  const steps=this.data.steps
  const idx=this.data.active
  if(steps[idx].taskStatus==0){
    if(steps[idx].requiresInterlock){
      $.toast('请点击当前步骤申请蓝牙锁权限，审核通过方可进行下一步')
      return false
    }
    if((steps[idx].tagNoClosing||steps[idx].tagGrounded||steps[idx].tagWorkHere||steps[idx].tagNoClosingStatus||steps[idx].interlockStatus)){
      $.toast('请点击当前步骤上传图片，审核通过方可进行下一步')
      return false
    }
    if((steps[idx].checkSwitch)){
      $.toast('请点击当前步骤上传图片，审核通过方可进行下一步')
      return false
    }
    api.$get(api.operateTicket.operationSubmitTask,{
      ticketNumber:this.data.ticketNumber,
      taskId:steps[idx].taskId
    }).then((res) => {
      this.getOperateList()
    })
  }else{
    const last= steps[idx];
      if((last.tagGrounded!= 0 && last.tagGroundedConfirmed==1)|| (last.tagNoClosing!= 0 && last.tagNoClosingConfirmed==1) ||(last.tagWorkHere!= 0 && last.tagWorkHereConfirmed==1) ||(last.requiresInterlock!= 0 && last.interlockConfirmed==1)  ||(last.checkSwitch!= 0 && last.checkSwitchConfirmed==1) ){
        console.log("status 1")
        this.setData({active:this.data.active+1,mainEquipImage:''})
      }else if(last.tagGrounded==0 && last.tagNoClosing==0 && last.tagWorkHere==0 && last.requiresInterlock==0 && last.checkSwitch==0 ){
        console.log("status 2")
        this.setData({active:this.data.active+1,mainEquipImage:''})
      }else {
        $.toast('请等待值班中心人员审核通过方可进行下一步')
        return false
      }
  }
},
beginSign(e){  
  var that=this
  if(!Boolean(that.data.signImg)){
    Store.dispatch({
      type: 'SET_FROM',
      form: {
        key: 'operateSign', 
      },
    })
    $.linkurl(`/pages/components/signatrue/signAture?ticketNumber=${that.data.ticketNumber}`) 
  }
  // wx.showModal({
  //   title: '提示',
  //   content: '使用原有签名或者手动签名',
  //   confirmText:'原有签名',
  //   cancelText:'手动签名',
  //   success (res) {
  //     if (res.confirm) {
  //       that.setData({
  //         signImg: wx.getStorageSync('signUrl'),
  //       })
  //     } else if (res.cancel) {
  //       Store.dispatch({
  //         type: 'SET_FROM',
  //         form: {
  //           key: 'operateSign', 
  //         },
  //       })
  //       $.linkurl(`/pages/components/signatrue/signAture?ticketNumber=${that.data.ticketNumber}`) 
  //     }
  //   }
  // }) 
},
bigSign(e){
  const {img}=$.detail(e)
  wx.previewImage({
    current: '', // 当前显示图片的链接，不填则默认为urls的第一张
    urls: [img] // 需要预览的图片链接列表
  })
},
cancelBack(e){
  $.linkurl('', 'back')
},
endConfirm(url,approvalResult,approvalRemark){
  if(!Boolean(this.data.signImg)){
    return $.toast('当前无默认签名，请手动填写！')
  }
  api.$get(api.operateTicket[url],{
    ticketNumber:this.data.ticketNumber,
    signature:this.data.signImg,
    approvalResult:approvalResult,
    approvalRemark:approvalRemark,
  }).then((res) => {
    $.linkurl('','back')
  })
},
updateHandle(){
  console.log(this.data.active,this.data.type)
  if(this.data.steps[this.data.steps.length-1].taskStatus==1&&Boolean(this.data.signImg)){
    if(this.data.type=='操作人终结')this.endConfirm('operationEndConfirm',true,'')//操作人终结
    if(this.data.type=='监护人操作')this.endConfirm('guardianEndConfirm',true,'')//监护人操作
    if(this.data.type=='许可人终结')this.endConfirm('permitIssuerEndConfirm',true,'')//许可人终结
    if(this.data.type=='工作负责人终结')this.endConfirm('workLeaderEndConfirm',true,'')//工作负责人终结
  }else{
    $.toast('所有操作完成且签字后方可提交')
  }
  
  
},
input_handle(e){
  this.setData({
    [e.currentTarget.dataset.key]: e.detail.value
  })
},
signNoClosing(e){
  api.$get(api.operateTicket.signNoClosing,{
    ticketNumber:this.data.ticketNumber,
    taskId:this.data.taskId,
  }).then((res) => {
  })
},
unSignNoClosing(){
  api.$get(api.operateTicket.unSignNoClosing,{
    ticketNumber:this.data.ticketNumber,
    taskId:this.data.taskId,
  }).then((res) => {
  })
},
signTagGrounded(){
  api.$get(api.operateTicket.signTagGrounded,{
    ticketNumber:this.data.ticketNumber,
    taskId:this.data.taskId,
  }).then((res) => {
  })
},
unSignTagGrounded(){
  api.$get(api.operateTicket.unSignTagGrounded,{
    ticketNumber:this.data.ticketNumber,
    taskId:this.data.taskId,
  }).then((res) => {
  })
},
signWorkHere(){
  api.$get(api.operateTicket.signWorkHere,{
    ticketNumber:this.data.ticketNumber,
    taskId:this.data.taskId,
  }).then((res) => {
  })
},
unSignWorkHere(){
  api.$get(api.operateTicket.unSignWorkHere,{
    ticketNumber:this.data.ticketNumber,
    taskId:this.data.taskId,
  }).then((res) => {
  })
}

})